import React,{useState} from 'react';
import * as XLSX from 'xlsx';
import {Card,Space,Modal,Button, Checkbox, Form, Input,Radio} from 'antd';
import {CloseOutlined,CloseSquareOutlined} from '@ant-design/icons';
import jsonSvg from './JSON.svg';
import excelSvg from './EXCEL.svg';

import styles from './index.module.scss';
import { req } from '@/common/methods';
import { useEffect } from 'react';
import Loading from '@/components/Loading/index.tsx';

const {Meta} = Card;

const Export = () => {
    const [loading,setLoading] = useState(true);
    const [dataCategory,setDataCategory] = useState([]);
    const fetchCategoryData = () => {
        req('/api/category/get').then(data => {
            setDataCategory(data);
            setLoading(false);
        }).catch(error => {
            Modal.error({
                title:'页面初始化错误',
                content:<>无法获取分类初始化数据,{''+error}</>
            })
        });
    }
    useEffect(() => {
        fetchCategoryData();
    },[]);
    const onGenerateExcelFormFinish = (values) => {
        const {category,allData} = values;
        //console.log(allData,'XLSX',XLSX);
        const currentCategory = dataCategory.find(item => item.id === category);
        if(!currentCategory){
            Modal.error({
                title:'错误',
                content:<>无法获取类别！</>
            });
            return;
        }
        const goods = (()=>{
            const goodsProto = allData.goods.filter(item => item.category === currentCategory.id && !item.delete_time);
            const res = goodsProto.map(item => {
                return {
                    '进货时间':(item.create_time || '').substring(0,10),
                    '名称':item.name,
                    '简介':item.detail,
                    '规格':item.specs,
                    '单位':item.unit,
                    '数量':item.count,
                    '别名':item.another_name,
                    '最后修改时间':(item.update_time || '').substring(0,10),
                }
            })
            return res;
        })();
        const categoryMap = {};
        allData.goods.forEach((item0) => {
            categoryMap[item0.id] = item0.category;
        });
        //console.log(categoryMap);
        //return;
        const getDaily = (method/*10,20,30*/,isIn/*true>0,false<0*/)=>{
            const proto = allData.daily.filter(item => categoryMap[item.goods_id] === category && item.method === method && (method !== 30 ? (isIn?item.change_count > 0:item.change_count < 0) : true) && !item.delete_time);
            
            const res = proto.map(item1 => {
                const find = allData.goods.find(item2 => item2.id === item1.goods_id);
                return {
                    [(isIn?'入库':'出库') + '方式']:{
                        10:item1.change_count > 0?'进货':'退货',
                        20:item1.change_count > 0?'收回':'领用',
                        30:item1.change_count > 0?'盘盈':'盘亏',
                    }[item1.method] || '未知',
                    '物品名称':(find && find.name) ? ('' + find.name):'',
                    '规格':(find && find.specs) ? ('' + find.specs):'',
                    '单位':(find && find.unit) ? ('' + find.unit):'',
                    '数量':Math.abs(item1.change_count),
                    '结余':item1.after_count,
                    [method === 10?'供货商':'部门']:(()=>{
                        const preProto = method === 10 ? allData.suppliers : allData.depart;
                        const find = preProto.find(item3 => item3.id === item1.depart);
                        if(find){
                            return find.name;
                        }else{
                            return `未知部门[${item1.depart}]`
                        }
                    })(),
                    [method === 10?(isIn?'进货人':'退货人'):'申请人']:item1.requ,
                    [method === 10?'确认人':(isIn?'交回人':'领用人')]:item1.empl,
                    '备注':item1.remark,
                    '时间':item1.time,
                    '单号':item1.doc_id,
                }
            })
            return res;
        }
        const sup_in = getDaily(10,true);
        const dep_in = getDaily(20,true);
        const sup_out = getDaily(10,false);
        const dep_out = getDaily(20,false);
        const inv = getDaily(30,true);
        // console.log('进货',sup_in);
        // console.log('领用',dep_out);
        // console.log('退货',sup_out);
        // console.log('收回',dep_in);
        // console.log('盘点',dep_in);
        //return;
        const xlsxObj = {
            SheetNames:['库存','进货','领用','退货','收回','盘点'],
            Sheets:{
                ['库存']:XLSX.utils.json_to_sheet([...goods]),
                ['进货']:XLSX.utils.json_to_sheet([...sup_in]),
                ['领用']:XLSX.utils.json_to_sheet([...dep_out]),
                ['退货']:XLSX.utils.json_to_sheet([...sup_out]),
                ['收回']:XLSX.utils.json_to_sheet([...dep_in]),
                ['盘点']:XLSX.utils.json_to_sheet([...inv])
            }
        }
        const date = new Date();
        XLSX.writeFile(xlsxObj,`(${date.getMonth()+1}.${date.getDate()}导出)${currentCategory.name} - ${(''+date.getHours())}.${date.getMinutes()}.xlsx`);
    }
    const onGenerateExcelFormFinishFailed = error => {
        Modal.error({title:'无法提交',content:<>请检查表单是否规范填写,参考:{''+error}</>})
    }
    return <>
        {loading?<Loading/>:<div className={styles.package}>
                <Card 
                    hoverable
                    style={{ width: 240 }}
                    cover={<img alt="导出为JSON" src={jsonSvg} />}
                    onClick={()=>{
                        req('/api/generate/all',{},'post').then((data) => {
                            const blob = new Blob([JSON.stringify({...data},null,2)],{
                                type:'application/json'
                            });
                            const url = URL.createObjectURL(blob);
                            const a = document.createElement('a');
                            a.setAttribute('href',url);
                            const date = new Date();
                            a.setAttribute('download',`(${date.getMonth() + 1}.${date.getDate()}导出)仓库管理系统数据${date.getTime()}.json`);
                            a.click();
                            //console.log(url);
                            Modal.info({
                                title:'导出为JSON',
                                content:<>正在导出，请留意下载对话框...</>
                            })
                        }).catch((error)=>{
                            Modal.error({
                                title:'错误',
                                content:<>无法生成JSON文件,{''+error}</>
                            })
                        })
                    }}
                >
                    <Meta title="导出为JSON" description="直接导出全部数据，便于MySQL数据库备份。" />
                </Card>
                <Card 
                    hoverable
                    style={{ width: 240 }}
                    cover={<img alt="导出为Excel" src={excelSvg} />}
                    onClick={()=>{
                        req('/api/generate/all',{},'post').then(data => {
                            Modal.info({
                                title:'导出为Excel',
                                content:<>
                                    <div className={styles.floatclose} onClick={()=>Modal.destroyAll()}>
                                        <CloseOutlined style={{fontSize:'20px'}} className={styles['close-icon']} />
                                    </div>
                                    <Form
                                        name="basic"
                                        labelCol={{ span: 8 }}
                                        wrapperCol={{ span: 16 }}
                                        style={{ maxWidth: 600 }}
                                        initialValues={{ remember: true }}
                                        onFinish={onGenerateExcelFormFinish}
                                        onFinishFailed={onGenerateExcelFormFinishFailed}
                                        autoComplete="off"
                                    >
                                        <Form.Item
                                            label="分类"
                                            name="category"
                                            rules={[{ required: true, message: '请选择分类' }]}
                                        >
                                            <Radio.Group>
                                                {dataCategory.map(item => 
                                                    <Radio value={item.id} key={item.id}>{item.name}</Radio>
                                                )}
                                            </Radio.Group>
                                        </Form.Item>
                                        <Form.Item label="所有数据" name="allData" initialValue={data} hidden>
                                            <Input/>
                                        </Form.Item>
                                        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                                            <Button type="primary" htmlType="submit">
                                                生成文件
                                            </Button>
                                        </Form.Item>
                                    </Form>
                                </>,
                                footer:false,
                            });
                        }).catch((error)=>{
                            Modal.error({
                                title:'错误',
                                content:<>{''+error}</>
                            });
                        })
                    }}
                >
                    <Meta title="导出为Excel" description="根据分类，导出为.xlsx文件，更直观、简洁。" />
                </Card>
        </div>}
    </>
}

export default Export